import {CheckCircleOutlined, PlusOutlined, UploadOutlined} from '@ant-design/icons';
import {
  Button,
  message,
  Drawer,
  FormInstance,
  Popconfirm,
  Image,
  InputNumber,
  Modal,
  Upload,
  Tag, Result, UploadProps, Spin,
} from 'antd';
import React, {useState, useRef} from 'react';
import {FooterToolbar} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormUploadButton,
  ProFormTextArea,
  ProFormDependency,
  ProFormFieldSet,
  ProFormRadio,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {
  removeData,
  dataList,
  addData,
  updateData,
  loadData,
  download,
  questionList,
  removeQuestionData,
  loadSelectTag, uploadPdf, uploadAuth, refreshUploadAuth, loadDataByHash, saveHash,
} from './service';
import type {CoursewareBody, CoursewareListItem, CoursewareListPagination} from './data';
import {QuestionItem} from './data';
import SparkMD5 from "spark-md5/spark-md5"
import OSS from '../../../aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min.js';

window.OSS = OSS;
import '../../../aliyun-upload-sdk/aliyun-upload-sdk-1.5.3.min.js';

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: CoursewareListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.coursewareId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleRemoveQuestion = async (coursewareId: number, selectedRows: QuestionItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeQuestionData(
      coursewareId,
      selectedRows.map((row) => row.questionId),
    );
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const requestTag = async () => {
  return loadSelectTag().then(({data}) => {
    return data;
  });
};

type CoursewareProps = {
  type?: number;
  keys?: React.Key[];
  selectMode?: boolean;
  onSelectData?: (keys: React.Key[], dataList: CoursewareListItem[]) => void;
};
const CoursewareList: React.FC<CoursewareProps> = (props) => {
    const {type, keys, selectMode, onSelectData} = props;
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [questionModalVisible, handleQuestionModalVisible] = useState<boolean>(false);
    const [questionModalTitle, handleQuestionModalTitle] = useState<string>('试题管理');
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const actionQuestionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<CoursewareListItem>();
    const [selectedRowsState, setSelectedRows] = useState<CoursewareListItem[]>([]);
    const columns: ProColumns<CoursewareListItem>[] = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 58,
        align: 'center',
        hideInTable: selectMode,
        valueType: 'indexBorder',
        render: (dom, entity, index) => {
          return (
            <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
          );
        },
      },
      {
        title: '课件名称',
        dataIndex: 'name',
      },
      {
        title: '标签',
        dataIndex: 'tags',
        valueType: 'select',
        fieldProps: {
          showSearch: true,
          mode: 'multiple',
        },
        request: requestTag,
        render: (_, record) => (
          <>
            {record?.tagNames?.map((name, index) => (
              <Tag key={name + index + record.coursewareId}>{name}</Tag>
            ))}
          </>
        ),
      },
      {
        search: false,
        title: '时长',
        dataIndex: 'time',
        render: (_, record) => (
          <>
            {Math.floor((record.time ?? 0) / 60)}分{(record.time ?? 0) % 60}秒
          </>
        ),
      },
      {
        search: false,
        title: '题数',
        dataIndex: 'questionNum',
        render: (_, record) => (
          <a
            onClick={() => {
              setCurrentRow(record);
              handleQuestionModalVisible(true);
              // handleQuestionModalTitle("试题管理" + "《" + record.name + "》");
              handleQuestionModalTitle('试题管理');
            }}
          >
            {record.questionNum}
          </a>
        ),
      },
      {
        title: '状态',
        sorter: false,
        hideInTable: selectMode,
        dataIndex: 'status',
        search: false,
        valueEnum: {
          1: {
            text: '禁用',
            status: 'Error',
          },
          0: {
            text: '正常',
            status: 'Success',
          },
        },
      },
      {
        title: '来源',
        sorter: false,
        hideInTable: true,
        dataIndex: 'kcSource',
        search: false,
      },
      {
        title: '提供者',
        sorter: false,
        hideInTable: true,
        dataIndex: 'kcAuthor',
        search: false,
      },
      {
        title: '备注',
        sorter: false,
        hideInTable: selectMode,
        dataIndex: 'remark',
        search: false,
      },
      {
        title: '更新时间',
        sorter: true,
        dataIndex: 'updateTime',
        valueType: 'dateTime',
        hideInTable: selectMode,
        search: false,
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        hideInTable: selectMode,
        hideInDescriptions: true,
        render: (_, record) => [
          <a
            key="view"
            onClick={() => {
              formRef.current?.resetFields();
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            查看
          </a>,
          <a
            key="edit"
            onClick={() => {
              formRef.current?.resetFields();
              console.log(record);
              setCurrentRow(record);
              setEditMode(true);
              handleModalVisible(true);
            }}
          >
            编辑
          </a>,
          <a
            key="question"
            onClick={() => {
              setCurrentRow(record);
              handleQuestionModalVisible(true);
              // handleQuestionModalTitle("试题管理" + "《" + record.name + "》");
              handleQuestionModalTitle('试题管理');
            }}
          >
            试题
          </a>,

          <Popconfirm
            key="delete"
            okButtonProps={{danger: true}}
            title={`确认删除课件：${record.name}?`}
            onConfirm={async () => {
              setCurrentRow(record);
              await handleRemove([record]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <a href="#"> 删除 </a>
          </Popconfirm>,
        ],
      },
    ];
    const questionColumns: ProColumns<QuestionItem>[] = [
      {
        title: '序号',
        dataIndex: 'index',
        valueType: 'indexBorder',
        render: (dom, entity, index) => {
          return (
            <span>
            {index +
              1 +
              ((actionQuestionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionQuestionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
          );
        },
      },
      {
        title: '题目',
        dataIndex: 'title',
      },
      {
        title: '选项',
        dataIndex: 'options',
        render: (_, record) => (
          <>
            {record?.options?.map((name, index) => (
              <div>
                <Tag
                  icon={name.answer ? <CheckCircleOutlined/> : <></>}
                  color={name.answer ? 'success' : ''}
                  key={name.key + index + record.questionId}
                >
                  {name.key}.{name.text}
                </Tag>
                <br/>
              </div>
            ))}
          </>
        ),
      },

      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        hideInDescriptions: true,
        render: (_, record) => [
          <Popconfirm
            key="delete"
            okButtonProps={{danger: true}}
            title={`确认删除?`}
            onConfirm={async () => {
              await handleRemoveQuestion(record.coursewareId, [record]);
              actionQuestionRef.current?.reloadAndRest?.();
              actionRef.current?.reload();
            }}
            okText="删除"
            cancelText="取消"
          >
            <a href="#"> 删除 </a>
          </Popconfirm>,
        ],
      },
    ];
    const [uploading, setUploading] = useState(false);
    const [spinning, setSpinning] = useState(false);
    const [spinningText, setSpinningText] = useState("上传中...");
    const [editMode, setEditMode] = useState<boolean>(false);
    const [previewData, setPreviewData] = useState({
      visible: false,
      image: '',
      title: '',
    });

    const uploadProps = {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
        TenantCode: 'e513f45c099239505054fead0a445fa2'
      },
      multiple: false,
      // onPreview: async (file: UploadFile) => {
      //   window.open(file?.response?.data?.path || file.url, '_blank')
      // },
      name: 'file',
      max: 1,
    };
    const submitCheckFile = (values: CoursewareBody, fileName: string, dataName: string) => {
      if (values[fileName]) {
        let file = values[fileName][0];
        values[dataName] = file?.response?.data?.url || file.url;
      }
    };

    const handleOk = () => {
      handleQuestionModalVisible(false);
    };

    const handleCancel = () => {
      handleQuestionModalVisible(false);
    };

    const addConfirm = (record: CoursewareListItem) => {
      Modal.confirm({
        icon: null,
        // title: '成功',
        content: <Result
          status="success"
          title="课件增加成功"
        />,
        okText: '上传试题',
        cancelText: '不上传',
        onOk: () => {
          setCurrentRow(record);
          handleQuestionModalVisible(true);
          // handleQuestionModalTitle("试题管理" + "《" + record.name + "》");
          handleQuestionModalTitle('试题管理');
        }
      });
    };
    const aa = () => {
      return new Promise((resolve, reject) => {
        let chunkSize = 1024 * 1024 * 20, // 20M
          chunks = Math.ceil(file.size / chunkSize),
          currentChunk = 0,
          spark = new SparkMD5.ArrayBuffer(),
          fileReader = new FileReader();
        // this.loading = this.$loading({text: '正在校验文件：' + (currentChunk / chunks * 100).toFixed(2) + '%'});
        fileReader.onload = (e) => {
          spark.append(e.target.result);
          currentChunk++;
          if (currentChunk < chunks) {
            console.log(1)
            // this.loading.setText('正在校验文件:' + (currentChunk / chunks * 100).toFixed(2) + '%')
            loadNext();
          } else {
            resolve(spark.end());
            // this.loading.close()
          }
        };

        fileReader.onerror = (e) => {
          reject(fileReader.error);
          reader.abort();
        };

        function loadNext() {
          let start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;
          fileReader.readAsArrayBuffer(file.slice(start, end));
        }

        loadNext();
      });
    }

    const getFileMd5 = (file) => {
      return new Promise((resolve, reject) => {
        let fileReader = new FileReader()

        fileReader.onload = function (event) {
          let fileMd5 = SparkMD5.ArrayBuffer.hash(event.target.result)
          resolve(fileMd5)
        }

        fileReader.readAsArrayBuffer(file)
      })
    }
    const uProps: UploadProps = {
      multiple: false,
      // showUploadList: false,
      maxCount: 1,
      accept: 'video/*,.pdf',
      customRequest: ({file, onSuccess, onProgress, onError}) => {
        console.log(file, "dddddddddd")

        // 判断文件类型
        const isVideoFile = /video\/(wmv|asf|asx|rm|rmvb|mpg|mpeg|mpe|3gp|mov|mp4|m4v|avi|dat|mkv|flv|vob)$/.test(file.type);
        const isPdf = /application\/pdf$/.test(file.type);
        console.log('是否为视频类型:', isVideoFile);
        console.log('是否为PDF:', isPdf);
        if (isVideoFile) {
          // 获取视频时长
          const url = URL.createObjectURL(file);
          const audioElement = new Audio(url);
          let videoSeconds;
          audioElement.addEventListener('loadedmetadata', (_event) => {
            videoSeconds = Math.floor(audioElement.duration);
            formRef.current?.setFieldsValue({time: videoSeconds});
            console.log('视频时长为', videoSeconds);
          });
        }
        let fName = file.name;
        formRef.current?.setFieldsValue({name: fName.slice(0, fName.lastIndexOf('.'))});
        getFileMd5(file).then((hash) => {
          console.log(hash)
          loadDataByHash(hash).then(({data}) => {
            if (data.id) {
              formRef.current?.setFieldsValue({url: data.path});
              formRef.current?.setFieldsValue({type: data.type});
              onSuccess(file);
            }
            if (isPdf && !data.id) {
              console.log(data)

              setSpinning(true);
              setSpinningText("上传中...");
              uploadPdf(file).then((res) => {
                formRef.current?.setFieldsValue({url: res.data.path});
                formRef.current?.setFieldsValue({type: res.data.type});
                console.log(res.data)
                setSpinning(false);
                onSuccess("done");
              })
            } else if (isVideoFile && !data.id) {
              // @ts-ignore
              const uploader = new AliyunUpload.Vod({
                //userID，必填，您可以使用阿里云账号访问账号中心（https://account.console.aliyun.com/），即可查看账号ID
                userId: '1378061344581407',
                //分片大小默认1 MB，不能小于100 KB（100*1024）
                partSize: 1048576,
                //并行上传分片个数，默认5
                parallel: 5,
                //网络原因失败时，重新上传次数，默认为3
                retryCount: 3,
                //网络原因失败时，重新上传间隔时间，默认为2秒
                retryDuration: 2,
                //开始上传
                onUploadstarted: (uploadInfo) => {
                  setSpinning(true);
                  console.log(uploadInfo);
                  uploadAuth({title: fName.slice(0, fName.lastIndexOf('.')), fileName: fName}).then((value) => {
                    console.log("v:", value)
                    let UploadAuth = value.data.uploadAuth
                    let UploadAddress = value.data.uploadAddress
                    let VideoId = value.data.videoId
                    formRef.current?.setFieldsValue({url: VideoId});
                    formRef.current?.setFieldsValue({type: 1});
                    uploader.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId);
                  });
                },
                //文件上传成功
                onUploadSucceed: function (uploadInfo: any) {
                  // uploader.stopUpload();
                  // onError(new Error('onUploadTokenExpired'));
                  // console.log('onUploadSucceed', uploadInfo);
                  onSuccess('done');
                },
                //文件上传失败
                onUploadFailed: function (uploadInfo, code, message) {
                  setSpinning(false);
                  onError(new Error(message));
                },
                //文件上传进度，单位：字节
                onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {
                  let percent = Math.round(loadedPercent * 100);
                  onProgress({percent}, file);
                  console.log('onUploadProgress', uploadInfo, totalSize, percent);
                  setSpinningText("" + percent + "上传中...");
                },
                //上传凭证或STS token超时
                onUploadTokenExpired: function (uploadInfo) {
                  onError(new Error('上传凭证或STS token超时'));
                  console.log('onUploadTokenExpired', uploadInfo);
                  if (uploadInfo.videoId) {
                    refreshUploadAuth({title: uploadInfo.videoId}).then((value) => {
                      let UploadAuth = value.data.uploadAuth
                      let UploadAddress = value.data.uploadAddress
                      let VideoId = value.data.videoId
                      uploader.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId);
                    })
                  }
                },
                //全部文件上传结束
                onUploadEnd: function (uploadInfo) {
                  console.log(formRef.current?.getFieldValue("url"), formRef.current?.getFieldValue("time"), "2333333333333")
                  saveHash({
                    "hash": hash,
                    "path": formRef.current?.getFieldValue("url"),
                  });
                  setSpinning(false);
                },
              });
              if (uploader) {
                uploader.stopUpload();
              }
              console.log(onProgress);
              uploader.addFile(file, null, null, null, '{"Vod":{}}');
              uploader.startUpload();
            }
          })
        })
      },
    };

    return (
      <>
        <ProTable<CoursewareListItem, CoursewareListPagination>
          headerTitle={'课件列表1'}
          actionRef={actionRef}
          rowKey="coursewareId"
          // manualRequest={true}
          pagination={{pageSize: selectMode ? 10 : 20}}
          // scroll={{x: 1200}}
          search={
            {
              // labelWidth: 120,
            }
          }
          form={{ignoreRules: false}}
          options={false}
          // @ts-ignore
          toolBarRender={() => {
            if (!selectMode) {
              return [
                <Button
                  type="primary"
                  key="primary"
                  onClick={() => {
                    setEditMode(false);
                    handleModalVisible(true);
                  }}
                >
                  <PlusOutlined/> 新建
                </Button>,
                <Upload {...uProps}>
                  <Button icon={<UploadOutlined/>}>上传</Button>
                </Upload>
              ];
            }
            return <></>;
          }}
          request={dataList}
          columns={columns}
          // @ts-ignore
          params={{
            type,
            includeSystem: selectMode,
            status: selectMode ? 0 : null,
            orderByColumn: selectMode ? 'questionNum' : undefined
          }}
          rowSelection={{
            type: type == 2 ? 'radio' : 'checkbox',
            selectedRowKeys: keys,
            preserveSelectedRowKeys: true,
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
              onSelectData && onSelectData(_, selectedRows);
            },
          }}
        />
        {selectedRowsState?.length > 0 && !selectMode && (
          <FooterToolbar
            extra={
              <div>
                已选择{' '}
                <a
                  style={{
                    fontWeight: 600,
                  }}
                >
                  {selectedRowsState.length}
                </a>{' '}
                个课件
              </div>
            }
          >
            <Popconfirm
              key="delete"
              title={`确认删除选中的${selectedRowsState.length}个课件?`}
              okButtonProps={{danger: true}}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <Button danger>批量删除</Button>
            </Popconfirm>
            {/*<Button type="primary">批量审批</Button>*/}
          </FooterToolbar>
        )}
        <ModalForm<CoursewareBody>
          title={currentRow?.coursewareId || 0 > 0 ? '编辑课件' : '新建课件'}
          formRef={formRef}
          layout={'horizontal'}
          labelCol={{span: 4}}
          wrapperCol={{span: 16}}
          visible={createModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          modalProps={{destroyOnClose: true, maskClosable: false}}

          onFinish={async (value) => {
            console.log(value);

            submitCheckFile(value, 'coursewareLicenceFile', 'coursewareLicence');
            submitCheckFile(value, 'operationCertificateFile', 'operationCertificate');
            submitCheckFile(value, 'coursewareInfoFile', 'coursewareInfo');
            submitCheckFile(value, 'maintainInfoFile', 'maintainInfo');
            console.log(value);


            const hide = message.loading(editMode ? '正在保存' : '正在添加');
            if (editMode) {
              try {
                await updateData({...value});
                hide();
                message.success('保存成功');
                handleModalVisible(false);
                // @ts-ignore
                actionRef?.current?.reloadAndRest();
              } catch (error) {
              }

            } else {
              try {
                let newVar1 = await addData({...value});
                debugger;
                hide();
                handleModalVisible(false);
                // @ts-ignore
                actionRef?.current?.reloadAndRest();
                addConfirm(newVar1.data);

              } catch (error) {
              }
            }
          }}
          // @ts-ignore
          request={(params: CoursewareBody) => {
            console.log(params);
            if (params.coursewareId > 0) {
              return loadData(params).then(({data}) => {
                if (data.url)
                  data.coursewareFile = [
                    {
                      url: data.url,
                      name: '课件',
                      status: 'done',
                    },
                  ];
                if (data.tags) data.tagList = data.tags;
                return data;
              });
            } else {
              return new Promise<CoursewareBody>((resolve) => {
                resolve({
                  coursewareId: 0,
                  status: 0,
                });
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="coursewareId"/>
          <ProFormText hidden name="time"/>
          <ProFormText hidden name="url"/>
          <ProFormText hidden name="type"/>
          <ProFormText hidden name="questionKey"/>

          <ProFormText rules={[{required: true}]} label={'课件名称'} name="name"/>

          <Spin tip={spinningText} spinning={spinning}>
            <ProFormUploadButton
              name="coursewareFile"
              label="上传课件"
              rules={[{required: true}]}
              max={1}
              extra={
                <div>
                  <div>支持mp4视频或者pdf文档</div>
                  <div>
                    <a href="http://images.51zasafe.com/dev/1606877737115.pdf" target="_blank">
                      上传视为同意视频上传协议
                    </a>
                  </div>
                </div>
              }
              // extra="请上传mp4视频或者pdf文档"
              // @ts-ignore
              fieldProps={{
                ...uProps,
              }}
            />

          </Spin>
          {/*<ProFormUploadButton*/}
          {/*  name="coursewareFile"*/}
          {/*  label="上传课件"*/}
          {/*  rules={[{required: true}]}*/}
          {/*  max={1}*/}
          {/*  extra={*/}
          {/*    <div>*/}
          {/*      <div>支持mp4视频或者pdf文档</div>*/}
          {/*      <div>*/}
          {/*        <a href="http://images.51zasafe.com/dev/1606877737115.pdf" target="_blank">*/}
          {/*          上传视为同意视频上传协议*/}
          {/*        </a>*/}
          {/*      </div>*/}
          {/*    </div>*/}
          {/*  }*/}
          {/*  // extra="请上传mp4视频或者pdf文档"*/}
          {/*  // @ts-ignore*/}
          {/*  fieldProps={{*/}
          {/*    ...uploadProps,*/}
          {/*    accept: '.pdf,.mp4',*/}
          {/*    onChange({file}) {*/}
          {/*      if (file.status === 'done' && file.response.code !== 200) {*/}
          {/*        file.status = 'error';*/}
          {/*      } else if (file.status === 'done' && file.response.code === 200) {*/}
          {/*        formRef.current?.setFieldsValue({url: file.response.data.path});*/}
          {/*        formRef.current?.setFieldsValue({time: file.response.data.time});*/}
          {/*        formRef.current?.setFieldsValue({type: file.response.data.type});*/}
          {/*      }*/}
          {/*    },*/}
          {/*  }}*/}
          {/*  action="/v2/enterprise/train/courseware/upload"*/}
          {/*/>*/}

          <ProFormDependency name={['type']}>
            {({type}) => {
              // if (coursewareFile && coursewareFile[0] && coursewareFile[0].response) {
              //   console.log(coursewareFile[0].response);
              //   let data = coursewareFile[0].response.data;
              if (type === 2) {
                return (
                  <ProFormFieldSet
                    name="formatTime"
                    label="课件时长"
                    type="group"
                    required
                    rules={[
                      {
                        validator: async (_, value) => {
                          console.log(_, value);
                          const [minute, second] = value || [];
                          if (!minute && !second) {
                            throw new Error('请填写课件时长');
                          }
                        },
                      },
                    ]}
                    transform={(value: any) => ({
                      time: value[0] * 60 + value[1],
                      minute: value[0],
                      second: value[1],
                    })}
                  >
                    <InputNumber name="minute" addonAfter="分钟"/>
                    &nbsp;&nbsp;
                    <InputNumber name="second" addonAfter="秒"/>
                  </ProFormFieldSet>
                );
              }
              // }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormSelect
            name="tagList"
            label="课件标签"
            mode={'tags'}
            request={requestTag}
            valueEnum={{
              open: '未解决',
              closed: '已解决',
            }}
            placeholder="请选择课件标签，没有合适的标签可以直接输入"
            extra={<span style={{color: "#d19b1a"}}>没有合适的标签可以直接输入,禁止输入纯数字标签</span>}
            rules={[{required: true, message: '请设置课件标签!'}]}
          />
          <ProFormRadio.Group
            name="status"
            rules={[{required: true, message: '请选择是否启用'}]}
            label="是否启用"
            options={[
              {
                label: '启用',
                value: 0,
              },
              {
                label: '禁用',
                value: 1,
              },
            ]}
          />
          <ProFormText label={'课件来源'} name="kcSource"/>
          <ProFormText label={'课件提供者'} name="kcAuthor"/>
          <ProFormTextArea label={'备注'} name="remark"/>
        </ModalForm>

        <Modal
          title={questionModalTitle}
          visible={questionModalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
          destroyOnClose={true}
          footer={[
            <Button
              key="back"
              onClick={() => {
                handleQuestionModalVisible(false);
              }}
            >
              关闭
            </Button>,
          ]}
          bodyStyle={{padding: 0}}
          width={800}
          maskClosable={false}
        >
          <ProTable<QuestionItem>
            options={false}
            request={async () => {
              let newVar = await questionList(currentRow?.coursewareId ?? 0);
              console.log(newVar);
              return {
                data: newVar,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.length,
              };
              // return questionList(currentRow?.coursewareId).then(({data}) => {
              //   console.log(data, "00000000000000")
              //
              // });
            }}
            rowKey="questionId"
            bordered
            pagination={false}
            columns={questionColumns}
            search={false}
            actionRef={actionQuestionRef}
            dateFormatter="string"
            headerTitle="题目列表"
            toolBarRender={() => [
              <Button onClick={download} key={'download'}>
                下载模板
              </Button>,
              <Upload
                key="upload"
                {...uploadProps}
                accept={'.xls,.xlsx'}
                action={'/v2/enterprise/train/courseware/question/upload/' + currentRow?.coursewareId}
                showUploadList={false}
                onChange={async (data) => {
                  let file = data.file;
                  if (file.status === 'uploading') {
                    setUploading(true);
                  } else {
                    setUploading(false);
                  }
                  if (file.status === 'done' && file.response.code !== 200) {
                    message.error(file.response.msg);
                    file.status = 'error';
                  } else if (file.status === 'done' && file.response.code === 200) {
                    message.success('上传成功');
                    // @ts-ignore
                    actionQuestionRef?.current?.reloadAndRest();
                    // @ts-ignore
                    actionRef?.current?.reloadAndRest();
                  }
                }}
              >
                <Button type="primary" loading={uploading} icon={<UploadOutlined/>}>
                  导入题目
                </Button>
              </Upload>,
            ]}
          />
        </Modal>
        <Image
          width={200}
          style={{display: 'none'}}
          src={previewData.image}
          preview={{
            visible: previewData.visible,
            src: previewData.image,
            onVisibleChange: (value) => {
              setPreviewData({image: previewData.image, title: '', visible: value});
            },
          }}
        />
        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.coursewareId && (
            <ProDescriptions<CoursewareBody>
              column={1}
              bordered={true}
              title={'课件详情'}
              // @ts-ignore
              request={loadData}
              // layout={'vertical'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<CoursewareBody>[]}
            />
          )}
        </Drawer>
      </>
    );
  }
;

export default CoursewareList;
